import * as Koa from 'koa'
import * as WebSocket from 'ws'
import { handle } from './handle';
import { getRow } from './alicloud/tablestore';

const WebSocketServer = WebSocket.Server;
const app = new Koa();

const server = app.listen(7001);
const wss = new WebSocketServer({ server: server });

wss.on('connection', (ws, req) => {
    const ip = req.connection.remoteAddress;
    console.log(`[SERVER] connection() ${ip}`);
    ws.send(JSON.stringify({
        info: 'Connection established!',
        status: 1
    }));

    ws.on('message', async (message) => {
        try {
            const res = await handle(ws, message)
        } catch (error) {
            console.log(error)
        }
    })
})

wss.on('error', (err) => {
    console.log(err)
})

setInterval(async () => {
    try {
        const data = await getRow()
        console.log(data)
        wss.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(data))
            }
        })
    } catch (error) {
        console.log(error)
    }
}, 2000)